<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class WechatController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public $appid = 'wxf28875858a6fdfe1';
    public $secret = '9f82a8300362f4894e6d5ce7750865ea';

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->redirect('wx/index/index2.html');
    }

    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf28875858a6fdfe1&redirect_uri=http%3A%2F%2Fyky.0o0.top/wechat/hello&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    public function actionHello()//获取用户信息
    {
        $code = $_GET['code'];
        $state = $_GET['state'];
        $secret = '9f82a8300362f4894e6d5ce7750865ea';

        $res = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret=$secret&code=$code&grant_type=authorization_code");
        $res_json = json_decode($res);
        $token = $res_json->access_token;
        $openid = $res_json->openid;

        $info = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid&lang=zh_CN");
        $info_json = json_decode($info);

        var_dump($info_json);
    }

    //https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=wxf28875858a6fdfe1&scene=1000&template_id=Dh2sDSAUWdCRPkxyuTTgbIdOdd06MzFgVOqYswC42GY&redirect_url=http%3A%2F%2Fyky.0o0.top/wechat/send&reserved=test#wechat_redirect
    public function actionSend()//发送一次性消息
    {
        $openid = $_GET['openid'];
        $template_id = $_GET['template_id'];
        $action = $_GET['action'];
        $scene = $_GET['scene'];
        $reserved = $_GET['reserved'];

        $res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}");
        $res_json = json_decode($res);
        if(!$res_json->access_token) {
            var_dump($res);die;
        }
        $token = $res_json->access_token;

        $data = [
            'touser' => $openid,
            'template_id' => $template_id,
            'url' => 'http://yky.0o0.top/wx/index/detail.html',
//            'miniprogram' => [
//                'appid' => $this->appid,
//                'pagepath' => '1',
//            ],
            'scene' => '1000',
            'title' => '成功领取到一张优惠券',
            'data' => [
                'content' => [
                    'value' => '虾迷火锅（中海锦苑店）
优惠券金额:  ¥24.00
优惠商品:   大份香辣虾',
                    'color' => 'FFFFFF',
                ],
            ]

        ];
        //$data = json_encode($data);
        //var_dump($data);die;
        $res = $this->http_request("http://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=$token", $data);
        $res_json = json_decode($res);
        var_dump($res_json);

        $this->redirect('http://yky.0o0.top/wx/index/success.html');
    }

    public function actionKefu()//客服接口
    {
        $code = $_GET['code'];
        $state = $_GET['state'];
        $secret = '9f82a8300362f4894e6d5ce7750865ea';

        $res = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret=$secret&code=$code&grant_type=authorization_code");
        $res_json = json_decode($res);
        $token = $res_json->access_token;
        $openid = $res_json->openid;

        $info = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid&lang=zh_CN");
        $info_json = json_decode($info);

        $res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}");
        $res_json = json_decode($res);
        $token = $res_json->access_token;

        $data = [
            'touser' => $openid,
            'msgtype' => 'text',
            'text' => [
                'content' => "亲爱的{$info_json->nickname}您已成功领取到一张优惠券!点击我的优惠券即可查看",
            ]
        ];
        //$data = json_encode($data);
        //var_dump($data);die;
        $res = $this->http_request("http://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token", $data);
        $res_json = json_decode($res);
        var_dump($info_json);

        return $this->redirect('/wx/index/index3.html');
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $data 键值对数据
     * @return string
     */
    function http_request($url, $data = null)
    {
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

        curl_setopt($curl, CURLOPT_USERAGENT ,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18");
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
